<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>reduce</title>
</head>
<body>
	<h1>reduce</h1>
</body>
<script type="text/javascript">
    const items = [10,120,1000];
    const item = items.reduce((pre,current,index,ary)=>{
        return pre+current;
    },0)
    console.log('item',item)


    // 将多层数组转换成一层数组
    const ary = [1,[2,[3,4,[5,6]]]];
    const aryReduce = (arr)=>{
        return arr.reduce((pre,current)=>{
            return pre.concat(Array.isArray(current)?aryReduce(current):current)
        },[])
    }
    console.log(aryReduce(ary))


    // 将下面数组转成对象，key/value 对应里层数组的两个值
    const objLikeArr = [["name", "Jim"], ["age", 18], ["single", true]];
    const fromPairs = pairs =>pairs.reduce((res, pair) => ((res[pair[0]] = pair[1]), res), {});
    console.log(fromPairs(objLikeArr))



    const objtest=[{key:'a',value:1},{key:'b',value:2},{key:'c',value:3}];
    const objFn = arr => arr.reduce((res,current)=>((res[current.key] = current.value),res),{})
    console.log(objFn(objtest))


    // 取出对象中的深层属性
    const deepAttr = { a: { b: { c: 15 } } }
    const pluckDeep = path => obj =>
    path.split(".").reduce((val, attr) => val[attr], obj);
    console.log(pluckDeep("a.b.c")(deepAttr))
    


    // 将用户中的男性和女性分别放到不同的数组里：
    const users = [
        { name: "Adam", age: 30, sex: "male" },
        { name: "Helen", age: 27, sex: "female" },
        { name: "Amy", age: 25, sex: "female" },
        { name: "Anthony", age: 23, sex: "male" },
    ];
    const partition = (arr, isValid) =>
    arr.reduce(
        ([pass, fail], elem) =>
        isValid(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]],
        [[], []],
    );
    const isMale = person => person.sex === "male";
    const [maleUser, femaleUser] = partition(users, isMale);
    console.log(maleUser,femaleUser)

</script>
</html>